#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <termios.h>
#include <pty.h>
#include <string.h>
#include <sys/signal.h>
#include <sys/ioctl.h>
#include <sys/stropts.h>

#include "base64.h"

#define SHELL "/bin/bash"
#define MSRGR2CLIENT "/tmp/m2c"
#define CLIENT2MSNGR "/tmp/c2m"
#define BUFFER_LENGTH 200
#define DATA_LENGTH 100

char *globalbuffer;
static struct termios tio, orig_termios, original;
int fd_c2m, fd_m2c;

void 
format (char the_buff[]) {
  int i;
  for (i = 93 ; i < 166 ; i++) {
    the_buff[i] = the_buff[i+4];
  }
  the_buff[i] = '\0';
}

void 
read_messenger() {
  int i, read_result, flag = 0;
  unsigned char *temp, target[DATA_LENGTH];
  char the_buff[BUFFER_LENGTH];
  size_t targetlen = DATA_LENGTH;
	
  do {
    if ((read_result = read (fd_m2c, the_buff, 170)) > 0) {
      i = 0;
      flag = 1;
      
      base64_decode (the_buff, target, targetlen);
      
      do {
	temp = &target[i++];
	printf ("%c", (*temp));
	if ((*temp) == '\0') {
	  break;
	}
	if (i == DATA_LENGTH) {
	  break;
	}
	
      } while (1); 
    }
    if (flag)
      if((*temp) == '\0')
	break;		
  } while (1);
}

void 
read_client ()
{
  int i = 7;
  char the_buffer, the_buff[170];
  the_buff[0] = 'p';
  the_buff[1] = 'i';
  the_buff[2] = 'd';
  the_buff[3] = 's';
  the_buff[4] = 's';
  the_buff[5] = 'h';
  the_buff[6] = ':';
  do {
    the_buffer = getc (stdin);
    if (the_buffer <= 0) {
      perror ("\nError : ");
      break;
    }	
    else {
      if (the_buffer == 0x4) {
	tcgetattr (0, &tio);
	tio = original;
	tcsetattr (0, 0, &tio);
	printf ("\nLogged out.\n");
	exit (0);
      }
      if (the_buffer == '\n') {
	the_buff[i++] = 'n';
	the_buff[i++] = 'e';
	the_buff[i++] = 'w';
	the_buff[i++] = 'l';
      }
      else
	the_buff[i++] = the_buffer;
    }	
    
    the_buff[i] = '\0';
    write (fd_c2m, the_buff, DATA_LENGTH);
    break;  
  } while (1);	
}

int 
main () {

  struct winsize window_size;
  tcgetattr (0, &orig_termios);
  original = orig_termios;
	
  orig_termios.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|IXON);
  orig_termios.c_oflag &= ~OPOST;
  orig_termios.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
  orig_termios.c_cflag &= ~(CSIZE|PARENB);
  orig_termios.c_cflag |= CS8;
  tcsetattr (0, 0, &orig_termios);

  unlink ("MSRGR2CLIENT");
  if (mkfifo ("MSRGR2CLIENT", 010777) == -1)
    perror ("\nError in mkfifo : ");
  if ((fd_m2c = open ("MSRGR2CLIENT",O_RDONLY|O_NONBLOCK)) < 0)
    perror ("\nError in opening fifo m2c\n");

  unlink ("CLIENT2MSNGR");
  if (mkfifo ("CLIENT2MSNGR", 010777) == -1)
    perror ("\nError in mkfifo : ");
  if ((fd_c2m = open ("CLIENT2MSNGR", O_WRONLY)) < 0)
    perror ("\nError in opening fifo c2m\n");

  ioctl (STDIN_FILENO, TIOCGWINSZ, &window_size);
  do {
      read_messenger ();
      read_client ();
  } while (1);

  return 0;
}
